/*
    This file is part of tPortal.

    tPortal is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    tPortal is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with tPortal.  If not, see <http://www.gnu.org/licenses/>.

    The original code was written by Sebastien Bettinger <sebastien.bettinger@gmail.com>

 */

package net.tinyportal.tools.taglib;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.portlet.PortletContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.IterationTag;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;

import net.tinyportal.Constant;
import net.tinyportal.bean.PortletHolder;
import net.tinyportal.javax.portlet.TpPortletContext;
import net.tinyportal.servlet.Portal;
import net.tinyportal.servlet.PortletLoader;

/**
 * La classe PortletsTag permet, par le taglib associé, de parcourir la liste
 * des portlets a afficher dans une page et les placer à tour de rôle
 * dans le contexte de la page. Ceux-ci peuvent alors être récupérer et
 * traiter dans la jsp.
 * @author seb0uil@gmail.com
 *
 */
public class PortletsTag extends TagSupport {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Liste des portlets de la page
	 */
	private List<PortletHolder> portlets;

	/**
	 * Index sur le portlet a afficher
	 */
	private int current = 0;

	private String portletName = null;

	public int doStartTag() throws JspException { 
		try {
			current = 0; 

			/**
			 * On recupère la liste des portlets de la page
			 */

			HttpServletRequest servletRequest = (HttpServletRequest)pageContext.getAttribute("javax.servlet.jsp.jspRequest");
			@SuppressWarnings("unchecked")
			Map<String, PortletHolder> portletsMap = (Map<String, PortletHolder>) servletRequest.getAttribute(Constant.session_portlet_bean_map);

			if (portletName == null) {
				portlets = new ArrayList<PortletHolder>(portletsMap.values());
				/**
				 * Ensuite, on place un à un les portlets dans
				 * l'attribut portlet afin de les récupérer 
				 */
				if (current < portlets.size()) {

					pageContext.setAttribute(Constant.session_portlet_bean, portlets.get(current) ); 
					return Tag.EVAL_BODY_INCLUDE; 
				}
			} else {
				if (portletsMap.containsKey(portletName)) {
					pageContext.setAttribute(Constant.session_portlet_bean, portletsMap.get(portletName) );
					return Tag.EVAL_BODY_INCLUDE; 
				} else {
					boolean find = false;
					for (String porltetMapsName: portletsMap.keySet()) {
						if (portletName.startsWith(porltetMapsName+ "//@")) {
							PortletLoader pLoader = new PortletLoader((ServletContext)pageContext.getAttribute("javax.servlet.jsp.jspApplication"));
							PortletContext portletContext = (TpPortletContext)portletsMap.get(porltetMapsName).getPortletConfig().getPortletContext();
							Map<String, PortletHolder> result = pLoader.load(new File(portletContext.getRealPath("")), porltetMapsName);
							
							PortletHolder portletHolder = result.get(porltetMapsName);
							
							Portal.addPortlet(portletName, portletHolder);
							portletsMap.put(portletName, portletHolder);
							find = true;
							break;
						}
					}
					if (find) {
						pageContext.setAttribute(Constant.session_portlet_bean, portletsMap.get(portletName) );
						return Tag.EVAL_BODY_INCLUDE; 
					} else {
						return Tag.SKIP_BODY;
					}
				}
			}
			return Tag.SKIP_BODY; 


		} catch (Exception e) {
			throw new JspException ("Error", e); 
		} 

	} 

	public int doAfterBody() throws JspException {
		if (portlets == null)
			return Tag.SKIP_BODY; 

		current++;
		if (current < portlets.size()) {
			pageContext.setAttribute(Constant.session_portlet_bean, portlets.get(current) );
			return IterationTag.EVAL_BODY_AGAIN; 
		} 
		return Tag.SKIP_BODY; 
	}

	public int doEndTag() throws JspException {
		pageContext.removeAttribute(Constant.session_portlet_bean); 
		return Tag.EVAL_PAGE;
	}

	public void setName(String portletName) {
		this.portletName = portletName;
	}
}
